import get_f from '@dfeidao/atom-nodejs/data/get-field';
import complex_query from '@dfeidao/atom-nodejs/db/complex-query';
import operate from '@dfeidao/atom-nodejs/db/operate';
import log from '@dfeidao/atom-nodejs/logger/log';
import call_service from '@dfeidao/atom-nodejs/msg/call-service';
import doc_code from '@dfeidao/atom-nodejs/msg/doc-code';
import { IncomingHttpHeaders } from 'http';
import { spaceid, systemid } from '../atom/config';
interface Message {

	params: {
		productid: string;
		class_id: string; // 班级编号
		class_name: string; // 班级名
		teacher_no: string; // 教师编号
		teacher_name: string; // 教师姓名
	};
}

interface IWebResult {
	data: unknown;
	cookie?: {
		[name: string]: string;
	} | null;
	content_type?: string;
	headers?: {
		[key: string]: string;
	};
	attachment?: string;
	redirect?: string;
	status_code?: number;
}

export default async function atom(message: Message, action_id: string, session_id: string, headers: IncomingHttpHeaders): Promise<IWebResult> {
	log('公众号推送消息 Service begin path:app-home/s003,action_id:' + action_id);
	// 公众号推送消息
	const query = complex_query(action_id, session_id, systemid);
	// 1、点击“确认签退”按钮根据"班级编号"和当前系统日期查询<签到>获取”学生编号““学生姓名”“家长编号”“家长姓名”
	const data = new Date();
	const check_in = await query
		.add_field('check_in', 'student_no', 'student_no') //
		.add_field('check_in', 'student_name', 'student_name') //
		.add_field('check_in', 'parent_number', 'parent_number') //
		.add_field('check_in', 'parent_name', 'parent_name') //
		.where_eq('check_in', 'class_id', message.params.class_id)
		.where_eq('check_in', 'productid', message.params.productid)
		.where_gte('check_in', 'arrive_time', data.setHours(0, 0, 0, 0))
		.where_lte('check_in', 'arrive_time', data.setHours(23, 59, 59, 999))
		.exec() as [{
			student_no: string,
			student_name: string,
			parent_number: string,
			parent_name: string
		}];
	if (check_in.length <= 0) {
		return { data: { code: 0, msg: '没有签到,无法签退' } };
	}
	// ，将“教师编号”“教师姓名”“学生编号”“学生姓名”“家长编号”“家长姓名”“班级编号”保存到<签退>表和<考勤记录>，“签退编号”和“考勤记录”据编码规则自动生成，“签退时间”和“记录编号”为当前系统时间，“签退状态”赋值为“1”，关闭弹窗
	const { exec, insert } = operate(action_id, session_id, systemid);
	const { results: sign_off_num } = await doc_code(action_id, session_id, systemid, 'BM0016038', '', check_in.length);
	const { results: check_attendance_info_num } = await doc_code(action_id, session_id, systemid, 'BM0016024', '', check_in.length);
	const time = new Date().getTime();
	check_in.forEach((v, i) => {
		// 签退
		insert('sign_off', { sign_off_num: sign_off_num[i], teacher_no: message.params.teacher_no, teacher_name: message.params.teacher_name, student_no: v.student_no, student_name: v.student_name, parent_number: v.parent_number, parent_name: v.parent_name, leave_time: time, productid: message.params.productid, sign_off_status: '1' });
		// 考勤记录
		insert('check_attendance_info', { check_attendance_info_num: check_attendance_info_num[i], student_no: v.student_no, student_name: v.student_name, class_id: message.params.class_id, teacher_no: message.params.teacher_no, class_name: message.params.class_name, teacher_name: message.params.teacher_name, supplementary_content: '', supplementary_time: 0, status: '4', record_time: time, productid: message.params.productid });
	});
	// 2、如果签退成功提示“签退成功”
	const res = await exec();
	log('公众号推送消息 @@@@@@@@@@@@@@@@@@@@@@@@' + res);
	if (res.code === 1) {
		try {
			// 1）依据选中的"班级编号"查询"<班级学生>表得到"学生编号",依据“学生编号”,"是否消息接收人"=1，查询<学生家长>，获取对应的“家长编号parent_number”"家长姓名",手机 phone”。
			const class_student = await query
				.add_field('class_student', 'student_no', 'student_no') // 学生编号
				.where_eq('class_student', 'class_id', message.params.class_id)
				.where_eq('class_student', 'productid', message.params.productid)
				.exec() as [{
					student_no: string
				}];
			const student_no = get_f(class_student, 'student_no');
			const parent_information = await query
				.add_field('parent_information', 'phone', 'phone') // 手机号i
				.add_field('parent_information', 'student_no', 'student_no') // 学生编号
				.add_field('parent_information', 'student_name', 'student_name') // 学生姓名
				.add_field('parent_information', 'parent_number', 'parent_number') // 家长编号
				.add_field('parent_information', 'parent_name', 'parent_name') // 家长姓名
				.where_in('parent_information', 'student_no', student_no)
				.where_eq('parent_information', 'productid', message.params.productid)
				.where_eq('parent_information', 'is_message_receiver', '1')
				.exec() as [{
					phone: string,
					student_no: string,
					student_name: string,
					parent_number: string,
					parent_name: string

				}];
			// （3）依据（2）得到的“手机 phone”查<pub_user_thirdpart_openid（12库）>表，获取对应的“openid”,
			const q_12 = complex_query(action_id, session_id, '12');
			const phone = get_f(parent_information, 'phone');
			const pub_user_thirdpart_openid = await q_12
				.add_field('pub_user_thirdpart_openid', 'usercode', 'usercode') //
				.add_field('pub_user_thirdpart_openid', 'openid', 'openid') //
				.where_eq('pub_user_thirdpart_openid', 'productid', message.params.productid)
				.where_in('pub_user_thirdpart_openid', 'usercode', phone)
				.exec() as [{ openid: string }];
			// 获取微信公众号授权token
			const { access_token } = await call_service(action_id, session_id, 'thirdpart.weixinpublicno', {
				"serviceflag": "getaccesstoken",      // 固定参数
				spaceid,           // 当前项目的spaceid
				"thirdpay_type": "weixin_pubno", // 固定参数（weixin_pubno）
				"productid": message.params.productid    // 当前登录用户对应的productid（从系统参数params中获取）
			});
			// (5) 5.2、依据"信息模板类型" = "1","信息模板状态"="1" 查询<信息模板>表,得到"信息模板内容"
			// 5.3、依据步骤7.3（1）得到“家长姓名”、“学生姓名”和依据步骤5.2得到"信息模板内容"，在"信息模板内容"中的@后拼接完成的信息模板内容
			// const information_template = await query
			// 	.add_field('information_template', 'information_template_content', 'information_template_content')
			// 	.where_eq('information_template', 'information_template_type', '2')
			// 	.where_eq('information_template', 'information_template_status', '1')
			// 	.where_eq('information_template', 'productid', message.params.productid)
			// 	.exec() as [{
			// 		information_template_content: string
			// 	}];
			const tousers = get_f(pub_user_thirdpart_openid, 'openid');
			// （6）调用接口向微信公众号定向推送消息
			const { code } = await call_service(action_id, session_id, 'thirdpart.weixinpubno.bulkpushmessage', {
				tousers,
				spaceid,
				access_token,
				custombody: {
					msgtype: "text",
					text: {
						content: `签退成功>>><a href=http://www.qq.com data-miniprogram-appid=wx76be1f60d92a519e data-miniprogram-path=pages/index/index>点击查看详情</a>`
					}
				}
			});
			log('公众号推送消息 Service end path:app-home/s003,action_id:' + action_id, code);

			if (code === 1) {
				return { data: { code: 1, msg: '签退成功' } };
			} else {
				return { data: { code: 0, msg: '签退失败' } };
			}
		} catch (error) {
			return { data: { code: 1, msg: '签退成功' } };
		}
	} else {
		return { data: { code: 0, msg: '签退失败' } };
	}
}
